import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from "axios";
import { showDialog } from "vant";
import router from "@/router";
import "vant/es/dialog/style";
export const baseURL =
  process.env.NODE_ENV === "development"
    ? "http://localhost:8260"
    : "http://111.231.0.118:8260/";
let tokenFlag = true;
class Http {
  instance: AxiosInstance;
  constructor(baseURL: string) {
    this.instance = axios.create({
      baseURL,
      timeout: 5000,
      withCredentials: false,
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        "Access-Control-Allow-Origin": "*",
      },
    });
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data } = response;
        if (data.code === 401 && tokenFlag) {
          tokenFlag = false;
          showDialog({
            title: "登录已过期，请重新登录",
            confirmButtonColor: "#ffcd41",
          }).then(() => {
            router.push("/login");
          });
        } else if (data.code !== 401 || !tokenFlag) {
          tokenFlag = true;
        }
        return data;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }
  get<R = unknown>(
    url: string,
    query?: Record<string, string | number>,
    config?: Omit<AxiosRequestConfig, "params" | "url" | "method">
  ) {
    return this.instance.request<R>({
      ...config,
      url: url,
      params: query,
      method: "get",
    });
  }
  post<R = unknown>(
    url: string,
    query?: Record<string, any>,
    config?: Omit<AxiosRequestConfig, "params" | "url" | "method">
  ) {
    return this.instance.request<R>({
      ...config,
      url: url,
      params: query,
      method: "post",
    });
  }
  put<R = unknown>(
    url: string,
    query?: Record<string, string>,
    config?: Omit<AxiosRequestConfig, "params" | "url" | "method">
  ) {
    return this.instance.request<R>({
      ...config,
      url: url,
      params: query,
      method: "put",
    });
  }
  delete<R = unknown>(
    url: string,
    query?: Record<string, string>,
    config?: Omit<AxiosRequestConfig, "params" | "url" | "method">
  ) {
    return this.instance.request<R>({
      ...config,
      url: url,
      params: query,
      method: "delete",
    });
  }
}

export const http = new Http(baseURL);
